//
//  ELGuideViewController.swift
//  SinaWeiBo
//
//  Created by jiwang on 15/12/17.
//  Copyright © 2015年 jiwang. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class ELGuideViewController: UICollectionViewController , ELNewFeatureCellDelegate {
    
    private let itemCount = 4
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        self.collectionView!.registerClass(ELNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return itemCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ELNewFeatureCell
    
        cell.delegate = self
        cell.index = indexPath.item
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        let visibleIndexPath = collectionView.indexPathsForVisibleItems().last!
        
        if visibleIndexPath.item == itemCount - 1 {
            let startCell = collectionView.cellForItemAtIndexPath(visibleIndexPath) as! ELNewFeatureCell
            startCell .startButonAnimation()
//            startCell.showStartButton()
        }
    }
    
    ///点击开始 跳到主页面
    func changeViewController() {
        let mainWindow = UIApplication.sharedApplication().keyWindow
        mainWindow?.rootViewController = ELMainTabBarController()
        
        mainWindow?.addSubview(self.collectionView!)
        
        UIView.animateWithDuration(0.8, animations: { () -> Void in
            
            self.collectionView?.frame.origin.y -= (mainWindow?.bounds.height)!
            
            }) { (_) -> Void in
                self.collectionView?.removeFromSuperview()
        }
//        (UIApplication.sharedApplication().delegate as! AppDelegate).animationChangeViewController(ELMainTabBarController(), currentView: self.collectionView!)
    }
    
    deinit {
//        print("死了吗")
    }
}

//MARK: - 自定义cell
protocol ELNewFeatureCellDelegate : NSObjectProtocol {
    
    func changeViewController()
}

class ELNewFeatureCell: UICollectionViewCell {
    
    //设置代理属性
    weak var delegate : ELNewFeatureCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 私有属性
    ///根据页数换图片
    var index = 0 {
        didSet {
            featureImage.image = UIImage(named: "new_feature_\(index + 1)")
            //每当滚动设置图片是调用，不然cell 会重用
            hideStartButton()
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        featureImage.frame = self.contentView.bounds
    }
    
    private func prepareUI () {
        
        contentView.addSubview(featureImage)
        contentView.addSubview(startButton)
        
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        //为开始按钮添加约束
        ///中心对齐
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        ///距离底部160
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPointMake(0, -160))
    }
    
    ///显示开始按钮
    func showStartButton () {
        startButton.hidden = false
    }
    ///隐藏开始按钮
    func hideStartButton () {
        startButton.hidden = true
    }
    ///开始按钮动画
    func startButonAnimation () {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
        }
    }
    ///点击事件，点击切换到主控制器
    @objc private func startButtonClick () {
        delegate?.changeViewController()
    }
    
    //MARK: 懒加载
    ///新特性图片
    private lazy var featureImage : UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    ///开始按钮
    private lazy var startButton : UIButton = {
       let button = UIButton()
        
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        //添加点击事件
        button.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.hidden = true
        return button
    }()
}
